<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .one{
            position: absolute;
            top: 100px;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        .two{
            position: absolute;
            top: 200px;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>
<body>
    <div class="one"></div>
    <div class="two"></div>
    <button class="btn1">点击改变背景颜色</button>
    <button class="btn2">点击改变背景颜色</button>
<script>
        var div = document.querySelector(".one");
        var div1 = document.querySelector(".two");
        var btn = document.querySelector(".btn1");
        var btn1 = document.querySelector(".btn2");


//动画函数封装
function fn(obj,target,callback){

//清除定时器，确保只有一个定时器工作
clearInterval(obj.timer);

    //定时器设置  
    obj.timer = setInterval(function(){

        //步长设置
        var step = (target - obj.offsetLeft) / 10;
        step = step > 0 ? Math.ceil(step) : Math.floor(step);

        // 判断是否到达目标地点
        if(obj.offsetLeft >= target){
                clearInterval(obj.timer);
                callback();
            }

        // 定位赋值
        obj.style.left = obj.offsetLeft + step + "px";
    },30)
}
        // 设置点击监听事件并调用动画函数
        btn.addEventListener("click",function(){
            fn(div,500,function(){
                div.style.backgroundColor = "red";
            });
        });
        btn1.addEventListener("click",function(){
            fn(div,100,function(){
                div.style.backgroundColor = "pink";
            });
        })
    </script>
</body>
</html>